package com.ww.core.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.TextView;

public class MusicUtil {
    private static final String TAG = "->MusicUtil";
    /** 用于播放音乐 */
    public MediaPlayer mediaPlayer;
    /** 是否处于暂停状态，是为true，否为false */
    public boolean pause = false;
    private int playPosition; // 当前播放的位置
    private int playDuration; // 音乐播放的总时间
    private String mediaUrl; // 要播放的音乐地址
    private SeekBar skbProgress; // 显示音乐播放的进度，也可以指定音乐播放的进度
    private TextView textProgress; // 显示当前音乐已播放的时间
    private TextView maxProgress; // 显示当前音乐播放的总时间

    private Timer mTimer = new Timer(); // 通过定时器和Handler来更新进度条
    private TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            if (mediaPlayer == null) {
                return;
            }
            try {
                if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {
                    handleProgress.sendEmptyMessage(0);
                }
            } catch (IllegalStateException e){
                Log.e(TAG, "mTimerTask,run()", e);
            }
        }
    };
    private Handler handleProgress = new Handler() { // 更新进度的handler
        public void handleMessage(Message msg) {
            if (mediaPlayer == null) {
                return;
            }
            playPosition = mediaPlayer.getCurrentPosition();
            playDuration = mediaPlayer.getDuration();
            if (playDuration > 0) {
                skbProgress.setProgress(playPosition);
                textProgress.setText(formatTime(playPosition));
                maxProgress.setText(formatTime(playDuration));
            }
        };
    };

    public MusicUtil(String mediaUrl, SeekBar skb, TextView text, TextView max) {
        this.mediaUrl = mediaUrl;
        this.skbProgress = skb;
        this.textProgress = text;
        this.maxProgress = max;
        mTimer.schedule(mTimerTask, 0, 1000);
        Log.i(TAG, mediaUrl);
    }
    
    public MusicUtil(Context context,String mediaUrl) {
        this.mediaUrl = mediaUrl;
        this.skbProgress = new SeekBar(context);
        this.textProgress = new TextView(context);
        this.maxProgress = new TextView(context);
        mTimer.schedule(mTimerTask, 0, 1000);
        Log.i(TAG, mediaUrl);
    }

    // 监听事件 -------------------
    private OnBufferingUpdateListener bufferingUpdateListener = new OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            int max = skbProgress.getMax();
            int secondProgress = max * percent / 100;
            skbProgress.setSecondaryProgress(secondProgress);
        }
    };
    private OnPreparedListener preparedListener = new OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            Log.i(TAG, "MyPreparedListener,onPrepared()");
            if (mediaPlayer != null) {
                mediaPlayer.start();// 开始播放
                skbProgress.setMax(mediaPlayer.getDuration());
                if (playPosition > 0) {
                    mediaPlayer.seekTo(playPosition);
                }
            }
        }
    };
    private OnCompletionListener completionListener = new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            Log.i(TAG, "MyPreparedListener,onCompletion()");
        }
    };

    // ------------------- 监听事件end

    /**
     * 首次开始播放音乐
     */
    public void start() {
        Log.i(TAG, "start()");
        if (mediaPlayer == null) {
            try {
                mediaPlayer = new MediaPlayer();
                mediaPlayer
                        .setOnBufferingUpdateListener(bufferingUpdateListener);
                mediaPlayer.setOnPreparedListener(preparedListener);
                mediaPlayer.setOnCompletionListener(completionListener);
            } catch (Exception e) {
                Log.e(TAG, "start()", e);
            }
        }
        playNet(0);
    }

    /**
     * 如果正在播放音乐就暂停播放且返回true，如果处于暂停状态就继续播放且返回false
     */
    public boolean pause() {
        if (mediaPlayer == null) {
            return pause;
        }
        try {
            pause = mediaPlayer.isPlaying();
        } catch (IllegalStateException e) {
            Log.e(TAG, "pause()", e);
        }
        if (pause) { // 如果正在播放音乐就将其暂停
            mediaPlayer.pause();
        } else {
            mediaPlayer.start(); // 继续播放
        }
        Log.i(TAG, "pause="+pause);
        return pause;
    }

    /**
     * 停止播放音乐
     */
    public void stop() {
        Log.i(TAG, "stop()");
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        mediaPlayer = null;
    }

    /**
     * 指定位置播放
     * 
     * @param playPosition
     */
    public void play(int playPosition) {
        Log.i(TAG, "play("+playPosition+")");
        if (mediaPlayer != null) {
            try {
                mediaPlayer.seekTo(playPosition);
            } catch (IllegalStateException e) {
                Log.e(TAG, "play()", e);
            }
        }
    }

    /**
     * 联网播放音乐并指定播放开始的位置
     * 
     * @param playPosition
     */
    private void playNet(int playPosition) {
        try {
            mediaPlayer.reset(); // 把各项数据恢复到初始状态
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(mediaUrl);
            mediaPlayer.prepareAsync();
            // mediaPlayer.prepare();
            mediaPlayer.setLooping(false);
        } catch (IOException e) {
            Log.e(TAG, "playNet(),IOException", e);
        } catch (Exception e) {
            Log.e(TAG, "playNet(),Exception", e);
        }
    }

    /**
     * 
     * 功能描述：格式化音乐播放时显示的时间
     * 
     * @param timeMills
     */
    public String formatTime(long timeMills) {
        Date date = new Date(timeMills);
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss", Locale.CHINESE);
        return sdf.format(date);
    }

}